package com.hfzy.ihk.web.linkcall.controller.setting.learningAnalysis;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.util.uuid.base64uuid.UUIDs;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.calldata.entity.CallHistoryText;
import com.hfzy.ihk.facade.calldata.service.EsOptRmiService;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlow;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingPackage;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.KnowledgeBase;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.QuestionBase;
import com.hfzy.ihk.facade.linkcall.enums.QuestionStatus;
import com.hfzy.ihk.facade.linkcall.vo.knowledgeBase.KnowledgeBaseVo;
import com.hfzy.ihk.web.linkcall.biz.CallDataBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.KnowledgeBaseBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.QuestionBaseBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingFlowBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingPackageBiz;
import com.hfzy.ihk.web.linkcall.utils.LayUiParamUtils;
import com.hfzy.ihk.web.linkcall.utils.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学习分析管理
 */
@Controller
@RequestMapping("/learningAnalysis")
public class LearningAnalysisController {

    Logger logger =LoggerFactory.getLogger(LearningAnalysisController.class);

    //注入问题学习的biz
    @Autowired
    private QuestionBaseBiz questionBaseBiz;

    @Reference(version = "1.0.0")
    private EsOptRmiService esOptRmiService;

    @Autowired
    private SpeakingFlowBiz speakingFlowBiz;


    @Autowired
    private KnowledgeBaseBiz knowledgeBaseBiz;

    @Autowired
    private SpeakingPackageBiz speakingPackageBiz;

    @Autowired
    CallDataBiz callDataBiz;

    @RequestMapping("/queryLearningAnalysis")
    public String queryLearningAnalysis(String packageId,Model model) {
        model.addAttribute("packageId",packageId);
        return "page/learningAnalysis/queryLearningAnalysis";
    }

    /**
     * 转跳到添加知识库KnowledgeBase问题页面
     *
     * @return
     */
    @RequestMapping("/addLearningAnalysis")
    public String addLearningAnalysis() {

        return "page/learningAnalysis/addLearningAnalysis";
    }


    /**
     * 添加或者编辑已有的知识库KnowledgeBase
     *
     * @return
     */
    @RequestMapping("insertOrUpdate")
    @ResponseBody
    public WebResult insertOrUpdate(KnowledgeBaseVo knowledgeBaseVo, String qid) {

        WebResult result = questionBaseBiz.insertOrUpdate(knowledgeBaseVo, qid);

        return result;
    }

    ;
    /**
     *
     * 功能描述:用于页面ajax请求的SpeakingFlow
     *
     * @param: []
     * @return: java.util.List<com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlow>
     * @auther:
     * @date: 2018/8/16
     */
    @ResponseBody
    @RequestMapping("loadSkipFlow")
    public List<Map<String,String>> loadSkipFlow(String text){

        Map<String,Object> paramMap=new HashMap<>();

        paramMap.put("flowName",text);

        List<SpeakingFlow> speakingFlows = speakingFlowBiz.searchFilterSpeakingFlowByField(paramMap);

        //将数据转化为前台需要的List集合
        List<Map<String, String>> resultList = LayUiParamUtils.getInstance().getJquerySelectParams(speakingFlows, (resultMap, object) -> {
            resultMap.put("label", ((SpeakingFlow) object).getFlowName());
            resultMap.put("value", ((SpeakingFlow) object).getId());
        });
        return resultList;
    }



    /**
     * 功能描述: 返回layui表格数据的所需json
     *
     * @param: [key, page, limit]
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @auther:
     * @date: 2018/8/14
     */
    @RequestMapping("queryAllNeedStudyQuestionBase")
    @ResponseBody
    public Map<String, Object> queryAllNeedStudyQuestionBase(QuestionBase questionBase,String packageId,Integer page, Integer limit) {

        Map<String, Object> keyMap = new HashMap<>();

        if (questionBase.getQuestion() != null) {
            keyMap.put("question", questionBase.getQuestion());
        }

        if (questionBase.getStatus() != null) {
            keyMap.put("status", questionBase.getStatus());
        }

        if(StringUtil.isNotNull(packageId)){
            keyMap.put("packageId", packageId);
        }

        Map<String, Object> map = questionBaseBiz.queryQuestionBaseBySearch(keyMap, page, limit);

        return map;
    }

    ;


    /**
     * 功能描述:根据Id删除questionBase
     *
     * @param: [id]
     * @return: com.hfzy.ihk.common.web.WebResult
     * @auther:
     * @date: 2018/8/16
     */
    @RequestMapping("deleteById")
    @ResponseBody
    public WebResult deleteById(String id) {


        WebResult result = questionBaseBiz.esDeleteById(id);

        return result;
    }

    /**
     * 查询会话流程
     * @return
     */
    @RequestMapping("selectSkipFlowById")
    @ResponseBody
    public SpeakingFlow selectSkipFlowById(String id){

        SpeakingFlow speakingFlow = speakingFlowBiz.selectById(id);

        return speakingFlow;
    }


    @RequestMapping("/queryLearningAnalysisDetail")
    public String queryLearningAnalysisDetail() {
        return "page/learningAnalysis/queryLearningAnalysisDetail";
    }



    /**
     *返回前台需要搜索的问题下拉框
     * 功能描述:
     *
     * @param: [mutiSessionFlowText]
     * @return: java.util.List<java.util.Map<java.lang.String,java.lang.String>>
     * @auther:
     * @date: 2018/8/20
     */
    @ResponseBody
    @RequestMapping("loadKnowledgeBase")
    public List<Map<String,String>> loadKnowledgeBase(@RequestParam Map<String,String> paramMap){


        List<KnowledgeBase> knowledgeBases = knowledgeBaseBiz.searchKnowledgeBaseByField(paramMap);

        //工具类将数据转化为前台需要的List集合
        List<Map<String, String>> resultList= LayUiParamUtils.getInstance().getJquerySelectParams(knowledgeBases,(resultMap,object)->{
            resultMap.put("label",((KnowledgeBase)object).getTitle());
            resultMap.put("value", ((KnowledgeBase)object).getId());
        });

        return resultList;
    }


    /**
     *返回前台需要搜索的话术包
     * 功能描述:

     * @param: [speakingPackage]
     * @return: com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingPackage
     * @auther:
     * @date: 2018/10/10
     */
    @ResponseBody
    @RequestMapping("findSpeakingPackage")
    public SpeakingPackage findSpeakingPackage(SpeakingPackage speakingPackage){

        SpeakingPackage result=null;

        if (speakingPackage.getId()!=null){

             result = speakingPackageBiz.selectById(speakingPackage.getId());
        }

        return result;
    }

    /**
     *
     * 功能描述:添加未识别问题接口
     * @url:localhost:8880/linkcall/learningAnalysis/saveQuestion
     * @return: boolean
     * @auther:
     * @date: 2018/8/28
     */
    @RequestMapping("saveQuestion")
    @ResponseBody
    public String saveQuestion(String questionBaseJsonStr){

        boolean flag = false;


        if (!StringUtil.isNotNull(questionBaseJsonStr)){

            logger.debug("未识别的question的json字符串为null");

            return String.valueOf(flag);
        }else{

            logger.debug("未识别的question的json字符串为"+questionBaseJsonStr);

        }

        try {
            //将json字符串转化为QuestionBase
            QuestionBase questionBase= JSON.parseObject(questionBaseJsonStr,QuestionBase.class);

            //假如问题内容为空,直接返回失败
            if (!StringUtil.isNotNull(questionBase.getQuestion())){

                return String.valueOf(flag);
            }
            //添加Id
            questionBase.setId(UUIDs.base64UUID());

            //添加学习状态为待学习
            questionBase.setStatus(QuestionStatus.NOT_LEARN);

            //设置创建时间和修改时间
            questionBase.setCreateTime( new Date(System.currentTimeMillis()));
            questionBase.setModTime(questionBase.getCreateTime());

            //调用biz保存
            questionBase.setModUserId(UserUtils.getCurrentUserId()!=null?UserUtils.getCurrentUserId():0l);

            //开始插入时间
            long begin = System.currentTimeMillis();

            flag = questionBaseBiz.insert(questionBase);

            //结束插入时间
            long end = System.currentTimeMillis();

            logger.info("未识别问题保存成功,耗时"+(end-begin)+"毫秒");

        } catch (Exception e) {

            logger.debug("未识别问题保存出错");
            flag=false;
            e.printStackTrace();
        }

        return String.valueOf(flag);
    }


    /**
     *查詢未識別問題的通話記錄
     * @return
     */
    @RequestMapping("getCallHistoryTest")
    @ResponseBody
    public WebResult getCallHistoryTest(@RequestParam Map<String,Object> params){

        WebResult result=new WebResult();
        try {

            //List<CallHistoryText> callHistoryTexts = esOptRmiService.searchCallHistoryTextList(params);
            List<CallHistoryText> callHistoryTexts = callDataBiz.searchCallHistoryTextList(params);
            result.setCode(GlobalStatic.CODE_1);
            result.setMsg(GlobalStatic.SUCCESS);
            result.setTotal(callHistoryTexts.size());
            result.setRecords(callHistoryTexts);

        }catch (Exception e){
            e.printStackTrace();
            result.setTotal(0);
            result.setMsg(GlobalStatic.FAIL);
            result.setCode(GlobalStatic.CODE_0);
        }

        return result;
    }
    /**
     * 搜索问题
     * @param params
     * @return
     */
    @RequestMapping("searchQuestionBase")
    @ResponseBody
    public WebResult searchQuestionBase(@RequestParam  Map<String,Object> params){

        WebResult webResult=new WebResult();

        try {

            List<QuestionBase> questionBases = questionBaseBiz.searchByParam(params);
            webResult.setTotal(questionBases.size());
            webResult.setRecords(questionBases);

            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg(GlobalStatic.SUCCESS);

        }catch (Exception e){

            e.printStackTrace();
            logger.error("搜索QuestionBase出错");
            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setMsg(GlobalStatic.FAIL);

        }

        return  webResult;

    }




   /* @RequestMapping("testadll)
    @ResponseBody
    public String testadd(){

        List<QuestionBase> add=new ArrayList<>();

        QuestionBase questionBaseBiz=new QuestionBase();
        questionBaseBiz.setCreateTime(new Date());
        questionBaseBiz.setModTime(new Date());
        questionBaseBiz.setId(UUIDs.base64UUID());
        questionBaseBiz.setModUserId(1L);
        questionBaseBiz.setQuestion("采光2");
        questionBaseBiz.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz);

        QuestionBase questionBaseBiz1=new QuestionBase();
        questionBaseBiz1.setCreateTime(new Date());
        questionBaseBiz1.setModTime(new Date());
        questionBaseBiz1.setId(UUIDs.base64UUID());
        questionBaseBiz1.setModUserId(1L);
        questionBaseBiz1.setQuestion("漏光2");
        questionBaseBiz1.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz1.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz1);

        QuestionBase questionBaseBiz2=new QuestionBase();
        questionBaseBiz2.setCreateTime(new Date());
        questionBaseBiz2.setModTime(new Date());
        questionBaseBiz2.setId(UUIDs.base64UUID());
        questionBaseBiz2.setModUserId(1L);
        questionBaseBiz2.setQuestion("透光2");
        questionBaseBiz2.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz2.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz2);

        QuestionBase questionBaseBiz3=new QuestionBase();
        questionBaseBiz3.setCreateTime(new Date());
        questionBaseBiz3.setModTime(new Date());
        questionBaseBiz3.setId(UUIDs.base64UUID());
        questionBaseBiz3.setModUserId(1L);
        questionBaseBiz3.setQuestion("非光2");
        questionBaseBiz3.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz3.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz3);

        QuestionBase questionBaseBiz4=new QuestionBase();
        questionBaseBiz4.setCreateTime(new Date());
        questionBaseBiz4.setModTime(new Date());
        questionBaseBiz4.setId(UUIDs.base64UUID());
        questionBaseBiz4.setModUserId(1L);
        questionBaseBiz4.setQuestion("走光2");
        questionBaseBiz4.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz4.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz4);

        QuestionBase questionBaseBiz5=new QuestionBase();
        questionBaseBiz5.setCreateTime(new Date());
        questionBaseBiz5.setModTime(new Date());
        questionBaseBiz5.setId(UUIDs.base64UUID());
        questionBaseBiz5.setModUserId(1L);
        questionBaseBiz5.setQuestion("脱光2");
        questionBaseBiz5.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz5.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz5);

        this.questionBaseBiz.insertBatch(add);

        return "OK";
    };*/
}


//===================测试数据==========================
 /* @RequestMapping("testadll")
    @ResponseBody
    public String testadd(){

        List<QuestionBase> add=new ArrayList<>();

        QuestionBase questionBaseBiz=new QuestionBase();
        questionBaseBiz.setCreateTime(new Date());
        questionBaseBiz.setModTime(new Date());
        questionBaseBiz.setId(UUIDs.base64UUID());
        questionBaseBiz.setModUserId(1L);
        questionBaseBiz.setQuestion("采光");
        questionBaseBiz.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz);

        QuestionBase questionBaseBiz1=new QuestionBase();
        questionBaseBiz1.setCreateTime(new Date());
        questionBaseBiz1.setModTime(new Date());
        questionBaseBiz1.setId(UUIDs.base64UUID());
        questionBaseBiz1.setModUserId(1L);
        questionBaseBiz1.setQuestion("漏光");
        questionBaseBiz1.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz1.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz1);

        QuestionBase questionBaseBiz2=new QuestionBase();
        questionBaseBiz2.setCreateTime(new Date());
        questionBaseBiz2.setModTime(new Date());
        questionBaseBiz2.setId(UUIDs.base64UUID());
        questionBaseBiz2.setModUserId(1L);
        questionBaseBiz2.setQuestion("透光");
        questionBaseBiz2.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz2.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz2);

        QuestionBase questionBaseBiz3=new QuestionBase();
        questionBaseBiz3.setCreateTime(new Date());
        questionBaseBiz3.setModTime(new Date());
        questionBaseBiz3.setId(UUIDs.base64UUID());
        questionBaseBiz3.setModUserId(1L);
        questionBaseBiz3.setQuestion("非光");
        questionBaseBiz3.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz3.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz3);

        QuestionBase questionBaseBiz4=new QuestionBase();
        questionBaseBiz4.setCreateTime(new Date());
        questionBaseBiz4.setModTime(new Date());
        questionBaseBiz4.setId(UUIDs.base64UUID());
        questionBaseBiz4.setModUserId(1L);
        questionBaseBiz4.setQuestion("不知道什么光");
        questionBaseBiz4.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz4.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz4);

        QuestionBase questionBaseBiz5=new QuestionBase();
        questionBaseBiz5.setCreateTime(new Date());
        questionBaseBiz5.setModTime(new Date());
        questionBaseBiz5.setId(UUIDs.base64UUID());
        questionBaseBiz5.setModUserId(1L);
        questionBaseBiz5.setQuestion("死肥佬");
        questionBaseBiz5.setSourceCallHistoryId(UUIDs.base64UUID());
        questionBaseBiz5.setStatus(QuestionStatus.NOT_LEARN);
        add.add(questionBaseBiz5);

        this.questionBaseBiz.insertBatch(add);

        return "OK";
    };*/